//
// Created by hugan on 2020/11/16.
//

#include "VolumeUtil.h"

#define SAFE_RELEASE(p) { if(p) { (p)->Release(); (p)=NULL; } }


#pragma ide diagnostic ignored "hicpp-signed-bitwise"

VolumeUtil::VolumeUtil() {
//    std::cout << "VolumeUtil.init" << std::endl;
    CoInitialize(nullptr);//目前没深究,同一对象[创建,销毁]时使用不同线程的后果
    CoCreateInstance(__uuidof(MMDeviceEnumerator), nullptr, CLSCTX_ALL, __uuidof(IMMDeviceEnumerator),
                     (void **) &pDeviceEnumerator);
    pDeviceEnumerator->GetDefaultAudioEndpoint(EDataFlow::eRender, ERole::eMultimedia, &pDevice);
    pDevice->Activate(__uuidof(IAudioEndpointVolume), CLSCTX_ALL, nullptr, (void **) &pAudioEndpointVolume);
    pDevice->Activate(__uuidof(IAudioClient), CLSCTX_ALL, nullptr, (void **) &pAudioClient);
}

VolumeUtil::~VolumeUtil() {
    release();
}

void VolumeUtil::release() {
//    std::cout << "VolumeUtil.release" << std::endl;
    SAFE_RELEASE(pAudioClient)
    SAFE_RELEASE(pAudioEndpointVolume)
    SAFE_RELEASE(pDevice)
    SAFE_RELEASE(pDeviceEnumerator)
    CoUninitialize();
}

bool VolumeUtil::isMute() {
    BOOL isMute;
    pAudioEndpointVolume->GetMute(&isMute);
    return isMute;
}

void VolumeUtil::setMute(bool v) {
    if (isMute() == v) return;
//    std::cout << "v=" << v << std::endl;
    pAudioEndpointVolume->SetMute(v, nullptr);
}

int VolumeUtil::getVolume() {
    float fVolume;
    pAudioEndpointVolume->GetMasterVolumeLevelScalar(&fVolume);
    return (int) std::round(fVolume * 100);
}

int VolumeUtil::setVolume(int v) {
    if (isMute()) pAudioEndpointVolume->SetMute(false, nullptr);//单纯setVolume是不会解除静音的
    if (v < 0) v = 0;
    else if (v > 100) v = 100;
    float fLevel = ((float) v) / 100;
//    std::cout << "fLevel=" << fLevel << std::endl;
    pAudioEndpointVolume->SetMasterVolumeLevelScalar(fLevel, nullptr);
    return v;
}


